//
//  HRHomeViewController.m
//  WestAir
//
//  Created by 张燕枭 on 16/8/28.
//  Copyright © 2016年 张燕枭. All rights reserved.
//

#import "HomeViewController.h"
#import "InventoryViewController.h"
#import "SellingViewController.h"
#import "AnnouncementDetails.h"
#import "LoginVC.h"

@interface HomeViewController (){

    NSString  *searchStr;
    CMCCIOTIGAlertControlCustomer  *alertControlCustomer;
}
@property(nonatomic,strong)NSArray *arrNotice;
@property (weak, nonatomic) IBOutlet UILabel *lableNotice;
@property(nonatomic,strong)NSString  *currentDate;
@property(nonatomic,strong)NSString  *currentHangBan;
@property(nonatomic,strong)UITextField  *textFieldSearch;

@property (weak, nonatomic) IBOutlet UIButton *btnSelectDate;
@property (weak, nonatomic) IBOutlet UIButton *btnSelectHangBan;

@end

@implementation HomeViewController

@synthesize dicMainData;

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self  initUIAndData ];
    
}

-(void)viewDidAppear:(BOOL)animated{
    
    
    
}

-(void)initUIAndData{
    
    [self  requestGongGao];
}

-(void)requestGongGao{
  
    NSDictionary  *dicJson=  [CMCCIOTIGUnity   getRequestJson:@{}];
    [[NetworkFactory  alloc]  startPostRequestWithURL:NOTICELIST andPostValues:dicJson andSuccessBlock:^(NSDictionary *responseJson) {
            
        if ([responseJson[@"IsSuccess"]  integerValue]==1) {
      
            NSArray  *arrNoticeList;
            if ([responseJson[@"NoticeList"]  isKindOfClass:[NSArray class] ]) {
                
                arrNoticeList=responseJson[@"NoticeList"];
            }
            else{
                arrNoticeList=@[];
            }
            
            _arrNotice=arrNoticeList;
            if (arrNoticeList.count) {
                NSDictionary  *dicNotice=arrNoticeList[0];
                NSString  *strNoticeList=dicNotice[@"FContent"];
                if ([strNoticeList  isKindOfClass:[NSString class]]) {
                    self.lableNotice.text=[NSString stringWithFormat:@"公告：%@",strNoticeList];
                }
                else{
                    self.lableNotice.text=[NSString stringWithFormat:@"公告：%@",@""];
                }
            }
            
        }
        
            
        } andFailBlock:^(NSError *error) {
           
            
        } ];
    

}

#pragma mark 跳转


//销售主持
- (IBAction)pushSalesExecutive:(id)sender {
    if ([self  shouldPerformSegueWithIdentifier:@"SalesExecutive" sender:@"SalesExecutive"]) {
        [self performSegueWithIdentifier:@"SalesExecutive" sender:@"SalesExecutive" ];
    }
   
}

// 信息反馈
- (IBAction)informationFeedback:(id)sender {
   
    if ([self  shouldPerformSegueWithIdentifier:@"InformationFeedback" sender:@"InformationFeedback"]) {
        [self performSegueWithIdentifier:@"InformationFeedback" sender:@"InformationFeedback" ];
    }
   
}

//配货盘点
- (IBAction)startSale:(id)sender {
   
  
        HangBanInfo  *hangBanInfo=[HangBanInfo  currentHangBan];
    
        if ([hangBanInfo.FIsInventory  isEqualToString:@"1"]) {
            
            
            if ([self  shouldPerformSegueWithIdentifier:@"sellViewController" sender:@"sellViewController"]) {
                [self performSegueWithIdentifier:@"sellViewController" sender:@"sellViewController" ];
            }
            
        }
        else{
         
            if ([self  shouldPerformSegueWithIdentifier:@"toInventory" sender:@"toInventory"]) {
                [self performSegueWithIdentifier:@"toInventory" sender:@"toInventory" ];
            }

           
        }
        
    }

// 信息查看
- (IBAction)informationSee:(id)sender {
  
        [self performSegueWithIdentifier:@"infromationSee" sender:@"infromationSee" ];
        ;
}

- (BOOL)shouldPerformSegueWithIdentifier:(NSString *)identifier sender:(nullable id)sender NS_AVAILABLE_IOS(6_0){
    
    //　先判断是否有航班信息
    if([HangBanInfo currentHangBan].FIsSucess){
        
        
    }
    else{
        [self alertSelectHangBanInfo];
        return NO;
    }
//  判断有权限没
    if([HangBanInfo currentHangBan].permissionCWY==0&&![identifier isEqualToString:@"shouHouPanDian"]) {
     
            [CMCCIOTTipsCenter  showAlertTitle:@"没有权限" message:@"" cancelTitle:@"" cancelBlock:nil quireTitle:@"确定" quireBlock:^(CMCCIOTIGAlertActionCustomer * _Nullable action) {
                ;
            }];
            return NO;
        
    }
    else if([HangBanInfo currentHangBan].permissionCK==0&&[identifier isEqualToString:@"shouHouPanDian"]){
        
            [CMCCIOTTipsCenter  showAlertTitle:@"没有权限" message:@"" cancelTitle:@"" cancelBlock:nil quireTitle:@"确定" quireBlock:^(CMCCIOTIGAlertActionCustomer * _Nullable action) {
                ;
            }];
            return NO;
        
        
    }

    MemberList   *currentUser=[MemberList currentUsinfo];
    if(([identifier isEqualToString:@"sellViewController"]||[identifier isEqualToString:@"toInventory"])&&![currentUser.FREADSALEPOLICY isEqualToString:@"1"]){
    
        [CMCCIOTTipsCenter  showAlertTitle:@"你还未阅读销售策略" message:@"" cancelTitle:@"" cancelBlock:nil quireTitle:@"确定" quireBlock:^(CMCCIOTIGAlertActionCustomer * _Nullable action) {
            
            ;
        }];
        return NO;
    
    }
    
    HangBanInfo *currentHangBan=[HangBanInfo currentHangBan];
    
    if(([identifier isEqualToString:@"sellViewController"]||[identifier isEqualToString:@"toInventory"])&&![currentHangBan.FSubmitSaleHost isEqualToString:@"1"] ){
        
        [CMCCIOTTipsCenter  showAlertTitle:@"请维护销售主持人" message:@"" cancelTitle:@"" cancelBlock:nil quireTitle:@"确定" quireBlock:^(CMCCIOTIGAlertActionCustomer * _Nullable action) {
            
            ;
        }];
        return NO;
        
    }
    
    
    
    return YES;


}


- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    

    if ([sender isKindOfClass:[NSString class]]) {
        if ([sender  isEqualToString:@"shouHouPanDian"]) {
            InventoryViewController  *destiner=segue.destinationViewController;
             destiner.saleType=saleAfter;
            destiner.title=@"售后盘点";
            
        }
        else if([sender  isEqualToString:@"toInventory"]){
            
             InventoryViewController  *destiner=segue.destinationViewController;
            
            HangBanInfo  *hangBan= [HangBanInfo  currentHangBan];
            
            if (![hangBan.FIsInventory  isEqualToString:@"1"]) {
                
                 destiner.saleType=startSales;
                 destiner.title=@"售前盘点";
                
                ;
            }

            
        }
    
    }
    
    
}

// 注销
- (IBAction)loginOutBtn:(id)sender {
    
    
    // 清空数据
    
    UIStoryboard *mainStory = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
    
    LoginVC *viewVC=  [mainStory instantiateViewControllerWithIdentifier:@"LoginVC"];
    
    UINavigationController  *nav=[[UINavigationController  alloc]  initWithRootViewController:viewVC];
    nav.navigationBar.hidden=YES;
    
    [UIApplication  sharedApplication].delegate.window.rootViewController=nav;
    
    [HangBanInfo currentHangBan].FIsSucess=NO;
    
    [[NSUserDefaults  standardUserDefaults]  setBool:NO forKey:ISMEMORY ];
    
}


// 售后盘点
- (IBAction)btnShouHouPanDian:(id)sender {
    
    
    if ([self  shouldPerformSegueWithIdentifier:@"shouHouPanDian" sender:@"shouHouPanDian"]) {
        [self performSegueWithIdentifier:@"shouHouPanDian" sender:@"shouHouPanDian" ];
    }

    
}


// 公告详情
- (IBAction)btnGoToGongGaoDetail:(id)sender {
    
    
    if (_arrNotice.count) {
        UIStoryboard *mainStory = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
        
        AnnouncementDetails *viewVC=  [mainStory instantiateViewControllerWithIdentifier:@"dd"];
        viewVC.arrData= _arrNotice;
        [self.navigationController pushViewController:viewVC animated:YES];
    }
    else{
    
        [CMCCIOTTipsCenter  showErrorWithStatus:@"暂无公告信息"];
    }
}


-(void)alertSelectHangBanInfo{
   
    
    [CMCCIOTTipsCenter  showAlertTitle:@"航班信息为空" message:@"" cancelTitle:@"" cancelBlock:nil quireTitle:@"确定" quireBlock:^(CMCCIOTIGAlertActionCustomer * _Nullable action) {
        ;
    }];

}


#pragma mark 选择航班号和日期


- (IBAction)btnSelectDate:(id)sender {
    
    NSArray  *arrAddressKey=[dicMainData  allKeys];
    
    arrAddressKey=[arrAddressKey sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"yyyy/MM/dd/"];
        if (obj1 == [NSNull null]) {
            obj1 = @"0000/00/00";
        }
        if (obj2 == [NSNull null]) {
            obj2 = @"0000/00/00";
        }
        NSDate *date1 = [formatter dateFromString:obj1];
        NSDate *date2 = [formatter dateFromString:obj2];
        NSComparisonResult result = [date1 compare:date2];
        return result == NSOrderedDescending;
    }];
   
    if (arrAddressKey.count==0) {
        [CMCCIOTTipsCenter showErrorWithStatus:@"暂无航班信息"];
        return;
    }
    
    NSMutableArray  *arrAction=[NSMutableArray new];
    for ( NSInteger i =0; i<arrAddressKey.count; i++) {
        
        NSString     *strDate=arrAddressKey[i];
        CMCCIOTIGAlertActionCustomer  *actionCustomer=  [CMCCIOTIGAlertActionCustomer  actionCustomerWithTitle:strDate style:UIAlertActionCustomeStyleDarkGray  handler:^(CMCCIOTIGAlertActionCustomer * _Nullable action) {
            
            if ([_currentDate isEqualToString:action.title]) {
                return ;
            }
            _currentDate= action.title;
            [_btnSelectDate  setTitle:_currentDate forState:UIControlStateNormal];
            _currentHangBan=nil;
            
            [self.btnSelectHangBan  setTitle:@"请选择航班" forState:UIControlStateNormal];
        }];
        
        BOOL  isSelect=[_currentDate  isEqual:strDate]?YES:NO;
        isSelect?[actionCustomer setIsSelect:YES]:nil;
        [arrAction addObject:actionCustomer];
        
    }
    [CMCCIOTTipsCenter   showAlertAddressTitle:@"选择日期" message:@"" arrAction:arrAction];
    
}
- (IBAction)selectHangBan:(id)sender {
    
    if (_currentDate==nil) {
        
        [CMCCIOTTipsCenter  showErrorWithStatus:@"日期不能为空"];
        return ;
    }
    
    NSArray  *arrAddressKey=dicMainData[_currentDate];
    [self  showDate:arrAddressKey];
    
}

-(void)showDate:(NSArray  *)arrAddressKey{


    NSMutableArray  *arrAction=[NSMutableArray new];
    
    for ( NSInteger i =0; i<arrAddressKey.count; i++) {
        
        NSString     *strHangBan=arrAddressKey[i];
        
        CMCCIOTIGAlertActionCustomer  *actionCustomer=  [CMCCIOTIGAlertActionCustomer  actionCustomerWithTitle:strHangBan style:UIAlertActionCustomeStyleDarkGray  handler:^(CMCCIOTIGAlertActionCustomer * _Nullable action) {
            
            _currentHangBan= action.title;
            
            [_btnSelectHangBan  setTitle:_currentHangBan forState:UIControlStateNormal];
            
            [self  requestHangBanDetail] ;
            
        }];
        
        BOOL  isSelect=[_currentHangBan  isEqual:strHangBan]?YES:NO;
        isSelect?[actionCustomer setIsSelect:YES]:nil;
        [arrAction addObject:actionCustomer];
        
    }
    
    alertControlCustomer= [CMCCIOTTipsCenter   showAlertAddressTitle:@"选择航班" message:@"" andTFOne:^(UITextField * _Nullable textField) {
        
        UIView  *leftView=[[UIView alloc]  initWithFrame:CGRectMake(0, 0, 20, 50)];
        textField.leftViewMode=UITextFieldViewModeAlways;
        textField.leftView=leftView;
        textField.placeholder=@"关键字搜索";
        _textFieldSearch=textField;
        ;
    } arrAction:arrAction];
    


}


- (void)requestHangBanDetail {
    

        NSDictionary  *dicParama=@{@"FNUMBER":_currentHangBan,@"FFLIGHTDATE":_currentDate,@"userAccount":[MemberList  currentUsinfo].userAccount };
        NSDictionary  *dicJson=  [CMCCIOTIGUnity   getRequestJson:dicParama];
        [[NetworkFactory  alloc]  startPostRequestWithURL:FLIGHTMENBERLIST andPostValues:dicJson andSuccessBlock:^(NSDictionary *responseJson) {
            
             HangBanInfo   *hangBan=[HangBanInfo  currentHangBan];
            if ([responseJson[@"IsSuccess"]  integerValue]==1) {
                
                
                NSArray  *arrData;
                if ([responseJson[@"data"] isKindOfClass:[NSArray  class]]) {
                    arrData=responseJson[@"data"];
                    
                }
                else{
                    arrData=@[];
                    
                }
                
                if(arrData.count){
                    NSDictionary  *dicData=arrData[0];
                    hangBan.priceListNo=[(NSString  *)responseJson[@"priceListNo"]  nullClass];
                    hangBan.FFLIGHTDATE=[(NSString  *)dicData[@"FFLIGHTDATE"]  nullClass];
                    hangBan.FFLIGHTNUMBER=_currentHangBan;
                    hangBan.permissionCK=[responseJson[@"permissionCK"]  integerValue];
                    hangBan.permissionCWY=[responseJson[@"permissionCWY"]  integerValue];
                    
                    hangBan.FID=[dicData[@"FID"]  integerValue];
                hangBan.FSubmitSalOrder=[dicData[@"FSubmitSalOrder"] nullClass];
                    hangBan.FSubmitSaleHost=[ (NSString  *)dicData[@"FSubmitSaleHost"]  nullClass];
                    
                    hangBan.FIsAuthorize=[ (NSString  *)dicData[@"FIsAuthorize"]  nullClass];
                    
                    
                    hangBan.FIsInventory=[(NSString  *)dicData[@"FIsInventory"]  nullClass];
                    hangBan.FIsInventoryHS=[(NSString  *)dicData[@"FIsInventoryHS"]  nullClass];
                    
                    
                    NSMutableArray  *arrMeber=[[NSMutableArray  alloc]  init];
                    
                    NSArray  *arrMemberParma;
                    
                    if([dicData[@"memberList"]  isKindOfClass:[NSArray  class]]){
                        
                        arrMemberParma=dicData[@"memberList"];
                    }
                    else{
                        
                        arrMemberParma=@[];
                    }
                    if (arrMemberParma.count) {
                      
                        for (int i=0; i<arrMemberParma.count; i++) {
                            MemberList  *member=[[MemberList  alloc]  init];
                            NSDictionary  *dicMember=arrMemberParma[i];
                            member.isSaleHost=[(NSString  *)dicMember[@"isSaleHost"]  nullClass];
                            member.userAccount=[(NSString  *)dicMember[@"userAccount"]  nullClass];
                            member.FEntryID=[STRING_FORMAT(dicMember[@"FEntryID"])  integerValue ]  ;
                            member.post=[dicMember[@"post"]  nullClass];
                            member.FREADSALEPOLICY=[dicMember[@"FREADSALEPOLICY"]  nullClass];
                        member.userID=[dicMember[@"userID"]  integerValue];
                            
                    
                            member.userName=[(NSString  *)dicMember[@"userName"]  nullClass];
                           
                            [arrMeber addObject:member];
                            
                            MemberList  *memberShare=[MemberList  currentUsinfo];
                            NSString  *userAccount=memberShare.userAccount;
                            NSString  *memberAccount=member.userAccount ;
                            if ([userAccount isEqualToString:memberAccount]) {
                                
                                [memberShare  setInfo:member];
                                
                            }
                            
                            
                        }
                        
                        hangBan.arrMember=arrMeber;
                        
                        
                        
                    }
                    
                    [HangBanInfo  currentHangBan].FIsSucess=YES;
                    
                }
                else{
                    
                    [CMCCIOTTipsCenter  showErrorWithStatus:@"暂无此航班信息"];
                     [HangBanInfo  currentHangBan  ].FIsSucess=NO;
                    return ;
                }
                
               
            }
            else{
               
                [HangBanInfo  currentHangBan  ].FIsSucess=NO;
                
            }
            
            
        } andFailBlock:^(NSError *error) {
           
            [HangBanInfo  currentHangBan  ].FIsSucess=NO;
        } ];
        
    }

-(void)popBack{
    
    [self.navigationController  popViewControllerAnimated:YES];
    
}

-(void)viewWillAppear:(BOOL)animated{

      [super viewWillAppear:animated];
     [[NSNotificationCenter     defaultCenter] addObserver:self selector:@selector(textDidChange:) name:UITextFieldTextDidChangeNotification object:_textFieldSearch];
}
-(void)textDidChange:(NSNotification *)object{
    
    UITextField  *text= [object  object];
    searchStr=text.text;
    searchStr = [searchStr stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    
    NSArray  *arrAddressKey=dicMainData[_currentDate];
    
    
    NSMutableArray  *arrSearch=[NSMutableArray  new];
    
    if (searchStr.length) {
        
        for (int i=0; i<arrAddressKey.count; i++) {
            
            NSString  *strHangBan=arrAddressKey[i];
            NSRange  searchRange= [strHangBan rangeOfString:searchStr];
            if (searchRange.length!=0) {
                
                [arrSearch addObject:strHangBan];
                
            }  ;
            
            ;
        }
    
    }
    else{
        arrSearch=[arrAddressKey   mutableCopy];
    }
    
    [alertControlCustomer.arrAlertAction   removeAllObjects ];
    
    for ( NSInteger i =0; i<arrSearch.count; i++) {
        
        NSString     *strHangBan=arrSearch[i];
        
        CMCCIOTIGAlertActionCustomer  *actionCustomer=  [CMCCIOTIGAlertActionCustomer  actionCustomerWithTitle:strHangBan style:UIAlertActionCustomeStyleDarkGray  handler:^(CMCCIOTIGAlertActionCustomer * _Nullable action) {
            
            _currentHangBan= action.title;
            
            [_btnSelectHangBan  setTitle:_currentHangBan forState:UIControlStateNormal];
            
            [self  requestHangBanDetail] ;
            
        }];
        
        BOOL  isSelect=[_currentHangBan  isEqual:strHangBan]?YES:NO;
        isSelect?[actionCustomer setIsSelect:YES]:nil;
        [alertControlCustomer addAction:actionCustomer];
        
        
    }

    [alertControlCustomer  reloadData];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

